package cn.lcfms.app.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Service;

import cn.lcfms.app.admin.bean.AreasBean;
import cn.lcfms.bin.App;
import cn.lcfms.bin.BaseService;

@Service
public class CommonService {
	/**
	 * 根据AreasBean中的id获取完整地址信息,必须省,市、州的id都有才有结果
	 * @param bean
	 * @return
	 */
	public String getAddress(AreasBean bean){
		BaseService service=App.getService("areas");
		StringBuffer sql=new StringBuffer();
		if(bean.getS_province()!=0){
			sql.append("select * from areas where id="+bean.getS_province());
		}
		if(bean.getS_city()!=0){
			sql.append(" union select * from areas where id="+bean.getS_city());
		}
		if(bean.getS_county()!=0){
			sql.append(" union select * from areas where id="+bean.getS_county());
		}
		if(bean.getS_street()!=0){
			sql.append(" union select * from areas where id="+bean.getS_street());
		}
		service.sql(sql.toString());
		List<HashMap<String, Object>> list = service.getResult();
		if(list.size()>=1){
			bean.setS_province_str((String)list.get(0).get("name"));
		}
		if(list.size()>=2){
			bean.setS_city_str((String)list.get(1).get("name"));
		}
		if(list.size()>=3){
			bean.setS_county_str((String)list.get(2).get("name"));
		}
		if(list.size()==4){
			bean.setS_street_str((String)list.get(3).get("name"));
		}
		return bean.toString();
	} 
	
	public String getAddress(int id){	
		List<String> list=new ArrayList<String>();
		getAddressById(id,list);
		StringBuffer buffer=new StringBuffer();
		for(int i=list.size()-1;i>=0;i--){
			buffer.append(list.get(i));
			if(i!=0){
				buffer.append("，");
			}
		}
		return buffer.toString();
	}
	
	private void getAddressById(long id,List<String> buffer){
		BaseService service=App.getService("areas");
		service.where("id="+id);
		HashMap<String, Object> map = service.selectMap();
		if(map==null){
			return;
		}
		long parent_id = (long) map.get("parent_id");
		if(parent_id!=0){
			buffer.add((String) map.get("name"));
			getAddressById(parent_id,buffer);
		}else{
			buffer.add((String) map.get("name"));
		}		
	}
}
